package cn.edu.sgu.www.mhxysy.service.gang.impl;

import cn.edu.sgu.www.mhxysy.pager.Pager;
import cn.edu.sgu.www.mhxysy.dto.gang.GangDTO;
import cn.edu.sgu.www.mhxysy.entity.gang.Gang;
import cn.edu.sgu.www.mhxysy.mapper.gang.GangMapper;
import cn.edu.sgu.www.mhxysy.pager.gang.GangPager;
import cn.edu.sgu.www.mhxysy.redis.repository.impl.GangRepository;
import cn.edu.sgu.www.mhxysy.service.gang.GangService;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class GangServiceImpl implements GangService {

	private final GangMapper gangMapper;
	private final GangRepository gangRepository;

	@Autowired
	public GangServiceImpl(GangMapper gangMapper, GangRepository gangRepository) {
		this.gangMapper = gangMapper;
		this.gangRepository = gangRepository;
	}

	@Override
	public void insert(GangDTO gangDTO) {
		Gang gang = toEntity(gangDTO);

		gangMapper.insert(gang);
	}

	@Override
	public void deleteById(String id) {
		gangMapper.deleteById(id);
	}

	@Override
	public void updateById(GangDTO gangDTO) {
		Gang gang = toEntity(gangDTO);

		gangMapper.updateById(gang);
	}

	@Override
	public List<Gang> selectAll() {
		return gangRepository.selectList();
	}

	@Override
	public Gang selectById(String id) {
		return gangRepository.selectById(id);
	}

	@Override
	public Page<Gang> selectByPage(GangPager pager) {
		QueryWrapper<Gang> queryWrapper = new QueryWrapper<>();
		Page<Gang> page = Pager.ofPage(pager);

		queryWrapper.like(
				StringUtils.isNotEmpty(pager.getName()),
				"name", pager.getName()
		);

		return gangMapper.selectPage(page, queryWrapper);
	}

	private Gang toEntity(GangDTO gangDTO) {
		Gang gang = new Gang();

		gang.setId(gangDTO.getId());
		gang.setName(gangDTO.getName());
		gang.setGrade(gangDTO.getGrade());
		gang.setBuilder(gangDTO.getBuilder());
		gang.setPurpose(gangDTO.getPurpose());
		gang.setServerId(gangDTO.getServerId());
		gang.setBuilderId(gangDTO.getBuilderId());

		return gang;
	}

}